package cn.gjxblog.realm;

import cn.gjxblog.entity.Permission;
import cn.gjxblog.entity.Role;
import cn.gjxblog.entity.User;
import cn.gjxblog.service.UserSerivce;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * 作用: 自定义数据源
 * 作者:gjx
 * 版本:V1.0
 */
public class MyRealm extends AuthorizingRealm {
    /**
     * 获取授权信息 角色信息+权限信息
     * @param principalCollection
     * @return
     */
    @Resource
    private UserSerivce userSerivce;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限认证...");

        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //添加角色
        List<Role> roles = userSerivce.findRoles(username);
        if(!roles.isEmpty()){
            for (Role role : roles) {
                info.addRole(role.getRoleTag());
            }
        }

        //添加权限
        List<Permission> permissions = userSerivce.findPermissions(username);
        if(!permissions.isEmpty()){
            for (Permission permission : permissions) {
                info.addStringPermission(permission.getPermissionTag());
            }
        }
        return info;
    }

    /**
     * 获取认证信息方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份认证....");
        UsernamePasswordToken usernamePasswordToken=  (UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();
        System.out.println(username);
        User user = userSerivce.findUserByName(username);

        if(user != null){
            String username1 = user.getUsername();
            String password = user.getPassword();
            String salt = user.getSalt();
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username1,password,ByteSource.Util.bytes(salt),UUID.randomUUID().toString());
            return simpleAuthenticationInfo;
        }

      return null;
    }
}
